const {app, router, pool} = require("../connect");

// 分页获取新闻列表
app.get('/study/getStudyLogList', function (req, res) {
    console.log("开始请求", req.query);
    let {pageSize = 10, pageNo = 1} = req.query;
    console.log('get:',req);
    let sql = `select * from study_log`;
    pool.getConnection((err, conn) => {
        if(err) throw err;
        conn.query(sql, (err, data) => {
            if(err) throw err;
            let total = data.length;
            let n = (pageNo - 1) * pageSize;
            sql += ` limit ${n}, ${pageSize}`;
            conn.query(sql, (_err, data) => {
                if(_err) throw _err;
                res.send({
                    code: 200,
                    data: {
                        content: data,
                        total: total,
                        pageNo: pageNo,
                        pageSize: pageSize
                    },
                    message: '查询成功'
                })
            })
        }) 
        pool.releaseConnection(conn);// 释放连接池
    })
});

// 添加新闻
app.post('/study/addStudyLog', (req, res) => {
    const data = req.body;
    const { title, content } = req.body;
    console.log('post:',req.body);
    const checkTitle = `select title from study_log where title='${title}'`;
    pool.getConnection((err, conn) => {
        conn.query(checkTitle, data, (_err, _result) => {
            console.log(_result);
            if(_result.length > 0){
                return res.json({
                    code: 0,
                    message: '标题重复，请重新拟定标题',
                    data: null
                })
            }else{
                const sql = `insert into study_log (title, content) values('${title}', '${content.toString()}')`;
                conn.query(sql, data, (err, result) => {
                    if(err) throw err;
                    res.json({
                        code: 200,
                        message: '添加成功',
                        data: result
                    })
                })
            }
        })
        pool.releaseConnection(conn);
    })
})

// 删除新闻
app.post("/study/deleteStudyLog", (req, res) => {
    let sql = `delete from study_log where id = ${req.body.id}`;
    pool.getConnection((err, conn) => {
        conn.query(sql, (err, result) => {
            if(err) throw err;
            res.json({
                code: 200,
                message: '删除成功',
                data: result
            })
        })
        pool.releaseConnection(conn);
    })
})

// 修改新闻
app.post("/study/updateStudyLog", (req, res) => {
    const { id, title, content } = req.body;
    let sql = `update study_log set title = '${title}', content = '${content}' where id = '${id}'`;
    console.log(sql)
    pool.getConnection((err, conn) => {
        conn.query(sql, (err, result) => {
            res.json({
                code: 200,
                message: "修改成功",
                data: result
            })
        })
    })
})

module.exports = router
